<template>
  <div :id="id">
    <Portal to="right-disable"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">

      <div style="height: 100%;">
        <el-card shadow="hover"
                 class="content-card"
                 :style="{height:gadgetHeight+ 'px',border:0}">
          <div>
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(widgetName && widgetName.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
              <span>
                <span class="cardTitle threepoints"
                      :title="widgetName"
                      v-if='widgetName && widgetName.trim().length>0'>{{ widgetName }}</span>
                <el-tooltip :open-delay="1000"
                            class="item"
                            v-if="(gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)||gadgetSetting.wikiUrl&&gadgetSetting.wikiUrl.trim().length>0"
                            effect="dark"
                            placement="right">
                  <div slot="content">
                    <div v-if='gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0'>{{gadgetSetting.headerDescription}}</div>
                    <div v-if="gadgetSetting.wikiUrl&&gadgetSetting.wikiUrl.trim().length>0"
                         style="margin-top:3px"><a :href="gadgetSetting.wikiUrl.trim()"
                         target="_blank"
                         style="color:#409eff">More Info</a></div>
                  </div>
                  <i class="cuifont icon_help_circle cardIcon"></i>
                </el-tooltip>
              </span>
              <span>
                <el-tooltip :open-delay="1000"
                            class="item"
                            effect="dark"
                            placement="right"
                            content="Refresh">
                  <i class="cuifont icon_arrow_sync"
                     style="float:right;margin-right:9px;cursor: pointer;"
                     @click="query()"></i>
                </el-tooltip>
              </span>
              <MoreMenu :slicer='slicer'
                        :fitToHeight='fitToHeight'
                        :gadgetId='id'
                        :gadgetType='gadgetInfo.com'
                        @updateQuery="query"
                        @fullScreen="fullScreen" />
            </div>
            <div v-show="isHasData"
                 class="content el-card__body"
                 :style="{'justify-content': 'center',height:gadgetHeight+ 'px'}">
              <div v-if="gadgetSetting.isShowAvatar"
                   style="margin-bottom: 140px;margin-left: 25px;display: flex;">
                <div>
                  <el-avatar :size="60"
                             :src="comFormatData.headUrl?comFormatData.headUrl:''">
                    <template slot="default">
                      <div style="white-space: nowrap;">
                        {{ comFormatData.realName }}
                      </div>
                    </template>
                  </el-avatar>
                </div>
                <div>
                  <span style="margin-left: 20px;font-weight: 400;"
                        :style="{color:gadgetSetting.footerTitleFontColor,fontSize:gadgetSetting.footerTitleFontSize-4 + 'px'}">{{ comFormatData.realName }}
                  </span>
                  <a :href="'mailto:'+`${comFormatData.username}`"><i class="el-icon-s-promotion"></i></a>
                  <br>
                  <span style="margin-left: 20px;"
                        :style="{color:gadgetSetting.footerTitleFontColor,fontSize:gadgetSetting.footerTitleFontSize-14+ 'px' }">{{ comFormatData.roleList }}</span>
                </div>
              </div>
              <div class="main"
                   ref="mainWidth"
                   :style="{marginTop:gadgetSetting.isShowAvatar?'-120px':'-65px'}">
                <span ref="valueFields"
                      :style="{'display':'inline-block',fontSize:gadgetSetting.valueFontSize + 'px','white-space': 'nowrap',color:gadgetSetting.valueFontColor }">
                  {{ formatCurrentTimeRecent }}
                </span>
                <br>
                <div v-if="gadgetSetting.footerTitle"
                     style="display: flex;justify-content: space-around;margin-bottom: 10px;">
                  <span style="text-align: center;display:'inline-block';margin-right: 26%;"
                        :style="{fontSize:gadgetSetting.footerTitleFontSize + 'px',color:gadgetSetting.footerTitleFontColor }">
                    {{'UTC '+ comFormatData.timezoneOffset}}
                  </span>
                  <span style="text-align: center;display:'inline-block';"
                        :style="{fontSize:gadgetSetting.footerTitleFontSize + 'px',color:gadgetSetting.footerTitleFontColor }">
                    {{ gadgetSetting.footerTitle }}
                  </span>
                </div>
              </div>
            </div>
            <div v-show="!isHasData"
                 class="gadget-no-newdata">
                    <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"  :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
            </div>

          </div>
        </el-card>
      </div>
      <Lastupdatetime v-if="currentTime"
                      :currentTime="currentTime"
                      :linkedDatasetList="linkedDatasetList"
                      @updateQuery="query()"></Lastupdatetime>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           :slicer='slicer' />
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import moment from 'moment'
export default ({
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: {
    Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model')
  },
  data: function () {
    return {
      formatCurrentTimeRecent: null,
      datesource: {
        value: '0'
      },
      currentTime: null,
      gadgetSetting: {},
      loading: false,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'usertimezoneinfocardgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'usertimezoneinfocardgadget' }).gadgetSetting
        }
      },
      widgetName: '',
      comFormatData: {
        headUrl: null,
        realName: null,
        roleList: [],
        timezoneId: null,
        timezoneName: null,
        timezoneOffset: null,
        username: null
      },
      valueFieldsWidth: null,
      isCenter: false,
      linkedDatasetList: [],
      userInfoList: [],
      currentDateTime: '',
      timers: null
    }
  },
  beforeDestroy () {
    clearInterval(this.timers)
  },
  updated () {
    if (this.$refs['valueFields']) {
      this.valueFieldsWidth = this.$refs.valueFields.clientWidth
      if ((this.valueFieldsWidth >= this.gadgetWidth - 10) && (this.gadgetSetting.valueFontSize > 12)) {
        this.isCenter = true
        if (this.$refs['mainWidth']) {
          this.gadgetWidth = this.$refs.mainWidth.clientWidth
        }
        this.fontSizeReduce()
      }
    }
  },
  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created () {
    this.gadgetHeight = this.pageFrom === 'reportLayoutFullScreen' ? window.screen.availHeight-100 :this.pageFromType === 'report' ? ((this.gadgetInfo.h * (this.rolHeight+10)-10) - 40) : ((this.gadgetInfo.h * 20) - 45)
    this.gadgetWidth = this.pageFrom === 'reportLayoutFullScreen' ? window.screen.width :(this.gadgetInfo.w * 7) * 19
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
  },
  methods: {
    fontSizeReduce () {
      this.gadgetSetting.valueFontSize -= 5
      this.gadgetSetting.footerTitleFontSize = parseInt(this.gadgetSetting.valueFontSize) / 8
      this.$forceUpdate()
      this.$nextTick(() => {
        if (this.$refs['valueFields']) {
          this.valueFieldsWidth = this.$refs.valueFields.clientWidth
          if ((this.valueFieldsWidth >= this.gadgetWidth - 10) && (this.gadgetSetting.valueFontSize > 12)) {
            this.fontSizeReduce()
          }
        }
      })
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetWidth = newWPx
      this.gadgetHeight = this.pageFromType === 'report' ? (newH * (this.rolHeight+10)-10) - 40 :(newH * 20) - 45
      if (this.gadgetWidth < this.gadgetHeight) {
        this.gadgetSetting.valueFontSize = Number(this.gadgetWidth) / 2.2
      } else {
        this.gadgetSetting.valueFontSize = Number(this.gadgetHeight) / 2.2
      }
      this.gadgetSetting.footerTitleFontSize = parseInt(this.gadgetSetting.valueFontSize) / 8
    },
    query (e) {
      if (e !== 'auto') {
        this.loading = true
      }
      this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName
      }
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        if (res.config) {
          _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
        }
        this.currentTime = new Date()
        if (res.name) {
          _self.widgetName = res.name
        } else if (this.wName) {
            _self.widgetName = this.wName
        } else {
          _self.widgetName = _self.gadgetSetting.headerTitle
        }
        this.queryUserInfo(e)
        // }
      }).catch(() => {
          if (this.wName) {
          this.widgetName = this.wName
        }
        this.loading = false
      }).finally(()=>{
        this.autoRefreshQuery(e)
        this.updateGadgetLoadingStatus(!this.loading)
      })
    },
    queryUserInfo (e) {
      const params = {
        status: 1
      }
      this.$interface.schedule.getWorkScheduledUserListApi(params).then(({ data: res }) => {
        this.verifyHasData(res)
        if (res.data) {
          this.userInfoList = res.data
          let temp = res.data.find(e => e.id === this.gadgetSetting.userId)
          if (temp) {
            this.widgetName = temp.realName
            let e = []
            for (let j = 0; j < temp.roleList.length; j++) {
              e.push(temp.roleList[j])
            }
            temp.roleList = e.join(', ')
            this.comFormatData = temp
            this.formatCurrentTime(this.comFormatData)
            clearInterval(this.timers)
            this.timers = setInterval(() => {
              this.formatCurrentTime(this.comFormatData)
            }, 1000)
          }
        }
      })
    },

    formatCurrentTime (data) {
      var timezone = data.timezoneId ? data.timezoneId : 'UTC'
      var currentDateTime = ''
      var hourFormat = this.gadgetSetting.hourTime ? 'HH:mm' : 'hh:mm a'
      if (timezone) {
        currentDateTime = moment.tz(moment().format(), timezone)
        this.gadgetSetting.footerTitle = moment(currentDateTime).format('dddd')
        if (this.gadgetWidth < this.gadgetHeight) {
          this.gadgetSetting.valueFontSize = Number(this.gadgetWidth) / 2.2
        } else {
          this.gadgetSetting.valueFontSize = Number(this.gadgetHeight) / 2.2
        }
        this.gadgetSetting.footerTitleFontSize = parseInt(this.gadgetSetting.valueFontSize) / 8
      }
      this.formatCurrentTimeRecent = currentDateTime.format(hourFormat)
    }
  }
})
</script>
<style lang="scss" scoped>
.content-card {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 45%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.content {
  display: flex;
  /* justify-content: space-between; */
  flex-direction: column;
  height: 100%;
}

.header {
  display: flex;
  height: 32px;
  justify-content: space-around;
  text-align: center;
  background: no-repeat;
  background-size: cover;
}

.main {
  display: block;
  /* justify-content: space-around; */
  text-align: center;
  /* margin-top: 35px; */
  padding: 5px 0 !important;
  /*height: 85px;*/
}

.footer {
  text-align: left;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardHeader > span {
  display: inline-block;
  width: calc(100% - 30px);
}

.cardTitle {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  display: inline-block;
  max-width: calc(100% - 30px);
  position: relative;
  top: 2px;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}
</style>
